package com.tsx.template.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tsx.template.common.constants.ResultMessage;
import com.tsx.template.common.constants.StatusCode;
import com.tsx.template.common.dto.AuthAssignPermissionDTO;
import com.tsx.template.common.exception.BusinessException;
import com.tsx.template.common.vo.AuthUserRoleVO;
import com.tsx.template.entity.AuthRole;
import com.tsx.template.entity.AuthRolePermission;
import com.tsx.template.mapper.AuthRolePermissionMapper;
import com.tsx.template.mapper.AuthUserRoleMapper;
import com.tsx.template.service.AuthRolePermissionService;
import com.tsx.template.service.AuthRoleService;
import com.tsx.template.mapper.AuthRoleMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Xuan
 * @description 针对表【auth_role(角色)】的数据库操作Service实现
 * @createDate 2024-04-03 12:04:02
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class AuthRoleServiceImpl extends ServiceImpl<AuthRoleMapper, AuthRole>
        implements AuthRoleService {
    // 角色权限mapper
    final AuthRolePermissionMapper authRolePermissionMapper;
    final AuthUserRoleMapper authUserRoleMapper;
    final AuthRoleMapper authRoleMapper;

    @Override
    @Transactional
    public void assignPermission(AuthAssignPermissionDTO authAssignPermissionDTO) {
        Integer roleId = authAssignPermissionDTO.getRoleId();
        // 先清空该角色下的所有权限
        authRolePermissionMapper.deleteByRoleId(roleId);
        // 要是该角色的权限是空
        if (authAssignPermissionDTO.getPermissions().isEmpty()) {
            return;
        }
        // 插入
        List<AuthRolePermission> authRolePermissions = authAssignPermissionDTO.getPermissions().stream()
                .map(pid -> new AuthRolePermission(roleId, pid)).toList();
        log.info("构造的集合对象:{}", authRolePermissions);
        authRolePermissionMapper.insertBatchRolePermission(authRolePermissions);
    }

    @Override
    @Transactional
    public void deleteWithUser(int id) {
        // 先删除对应关系
        authUserRoleMapper.deleteByRoleId(id);
        // 删除角色
        this.removeById(id);
    }
}




